﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：周传雄 
    //
    // 文件名：DistributePlanList.cs
    // 文件功能描述：发票管理
    // 创建标识：周传雄2009-05-12
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
using System.Collections.Generic;
using HZ.DrugTrade.Web;

namespace HZ.DrugTrade.Web.Enterprise.InvoiceManage
{
    public partial class InvoiceAdd : BasePage
    {
        string invoiceSerialID = "";
        string hositalID = "";
        //string str_satus = "";

        public InvoiceAdd()
        {
            this.ModuleNo = Module.发票管理.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            invoiceSerialID = Request["InvoiceSerialID"];
            hositalID = Request["hID"];
            //str_satus = Request["checkstatus"];
            //if (!string.IsNullOrEmpty(str_satus))
            //{
            //    if (str_satus == "1")
            //    {

            //    }
            //}
            if (string.IsNullOrEmpty(invoiceSerialID) || string.IsNullOrEmpty(hositalID))
            {
                Response.Write("<script> alter('非正常操作！'); document.location='InvocieList.aspx';</script>");
            }

            else if (!IsPostBack)
            {

                ShowData();
                ShowInvocieInfo();   //绑定发票基本信息
            }


        }
        /// <summary>
        /// 数据绑定[未开票]
        /// </summary>
        private void ShowGVW()
        {

        }

        /// <summary>
        /// 显示发票信息
        /// </summary>
        private void ShowInvocieInfo()
        {
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            Model.Query.Invoice qryCondition = new Model.Query.Invoice();
            qryCondition.InvoiceSerialID = Request["InvoiceSerialID"].ToString();
            int totalCount = 0;
            IList<Model.View.Invoice> invoiceList = iPurchase.GetInvoiceByWhere(qryCondition, 1, 0, out totalCount);
            if (invoiceList.Count > 0)
            {
                Model.View.Invoice invoice = iPurchase.GetInvoiceByWhere(qryCondition, 1, 0, out totalCount)[0];
                if (invoice != null)
                {
                    //if (invoice.AuditStatus.Value != 0)        //updated by lhl 2009-08-28
                    //{
                    //    btnAdd.Visible = false;
                    //    btnDel.Visible = false;
                    //}

                    txtInvoiceId.Text = invoice.InvoiceID;
                    txtAmount.Text = invoice.TotalAmount.ToString();
                    txtHospital.Text = invoice.HospitalName;
                    string status = invoice.AuditStatus.ToString();
                    if (status == "0")
                    {
                        txtStatus.Text = "未提交";
                        btnAdd.Enabled = true;
                        btnDel.Enabled = true;
                        btnSumbit.Enabled = true;
                    }
                    else if (status == "1")
                    {
                        txtStatus.Text = "已提交";
                        btnAdd.Enabled = false;
                        btnDel.Enabled = false;
                        btnSumbit.Enabled = false;
                    }
                }
                else
                {
                    PageError("给定发票不存在！", this.ReturnUrl);
                }
            }
            else
            {
                PageError("给定发票不存在！", "InvocieList.aspx");
            }
        }

        /// <summary>
        /// 发票详情
        /// </summary>
        private void ShowData()
        {

            IList<Model.View.InvoiceDistribution> ListInvoiceDistribution = new List<Model.View.InvoiceDistribution>();
            Model.Query.InvoiceDistribution qryCondition = new Model.Query.InvoiceDistribution();
            User user = CurrentAccount.GetUser();
            qryCondition.CompanyID_PS = user.Org.OrgID;
            qryCondition.InvoiceSerialID = invoiceSerialID;
            qryCondition.OrderName = txtOrderName.Text.ToString().Trim();
            qryCondition.GoodsName = txtGoodsName.Text.ToString().Trim();
            qryCondition.Material = txtMaterial.Text.ToString().Trim();
            qryCondition.PinyinCode = this.txtpinyincode.Text.Trim().ToUpper();
            qryCondition.Outlookc = txtOutLookc.Text.ToString().Trim();
            qryCondition.ProjectID = this.ddlProjectid.SelectedValue;
            //qryCondition.HospitalName = txtHospitalName.Text.ToString().Trim();
            qryCondition.DistributeTimeFrom = new HZ.Common.ConvertHelper(txtTimeFrom.Text.ToString().Trim()).ToDateTime;
            qryCondition.DistributeTimeTo = new HZ.Common.ConvertHelper(txtTimeTo.Text.ToString().Trim()).ToDateTime;
            qryCondition.CompanyName_SC = txtCompanyName.Text.Trim();
            qryCondition.SortFields = " DistributeTime desc ";
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            ListInvoiceDistribution = iPurchase.GetInvoiceDistributionByWhere(qryCondition, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            if (ListInvoiceDistribution.Count == 0)
            {
                btnDel.Enabled = btnSumbit.Enabled = false;
                //Repaired by sinodier 2011年1月13日0:08:18
                //没记录不能操作

            }
            else
            {
                btnDel.Enabled = btnSumbit.Enabled = true;
                //Repaired by sinodier 2011年1月13日0:08:18
                //有记录能操作
            }

            AspNetPager1.RecordCount = totalCount;
            gvwInvoiceAdd.DataSource = ListInvoiceDistribution;
            gvwInvoiceAdd.DataBind();

        }



        /// <summary>
        /// 删除发票明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDel_Click(object sender, EventArgs e)
        {
            IList<Distribution> LisDistribution = new List<Distribution>();
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            LisDistribution.Clear();

            string[] DistributionSerialIDs = Request.Form["ChkOrderID"].ToString().Split(',');
            string InvoiceSerialID = Request.QueryString["InvoiceSerialID"].ToString();


            foreach (var item in DistributionSerialIDs)
            {
                LisDistribution.Add(new Distribution() { DistributionSerialID = item });
            }
            Invoice invoice = new Invoice() { InvoiceSerialID = InvoiceSerialID };

            int nSuccess = iPurchase.DelInvoiceDistribution(invoice, LisDistribution);

            if (nSuccess == 1)
            {
                HZ.Web.WebUtil.Alert("操作成功", this);

                //Repaired by sinodier 2011年1月13日0:08:18
                //重新显示发票金额
                ShowInvocieInfo();

                ShowData();

            }
            else
            {
                HZ.Web.WebUtil.Alert("操作失败", this);
                return;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            ShowData();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("InvoiceDistribution.aspx?InvoiceSerialID=" + invoiceSerialID + "&hID=" + Server.UrlEncode(hositalID));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_back_Click(object sender, EventArgs e)
        {
            Response.Redirect("InvocieList.aspx");
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
        }


        /// <summary>
        /// 将此发票提交给医疗机构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSumbit_Click(object sender, EventArgs e)
        {
            if (gvwInvoiceAdd.Rows.Count <= 0)
            {
                HZ.Web.WebUtil.Alert("发票明细为空，无法提交无法提交该发票！");
                return;
            }
            IList<Model.View.InvoiceDistribution> ListInvoiceDistribution = new List<Model.View.InvoiceDistribution>();
            Model.Query.InvoiceDistribution qryCondition = new Model.Query.InvoiceDistribution();
            User user = CurrentAccount.GetUser();
            qryCondition.CompanyID_PS = user.Org.OrgID;
            qryCondition.InvoiceSerialID = invoiceSerialID;


            int totalCount = 0;
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            ListInvoiceDistribution = iPurchase.GetInvoiceDistributionByWhere(qryCondition, 1, 0, out totalCount);
            string[] DistributionSerialID = new string[ListInvoiceDistribution.Count];
            for (int i = 0; i < ListInvoiceDistribution.Count; i++)
            {
                DistributionSerialID[i] = ListInvoiceDistribution[i].DistributionSerialID;
            }

            List<Invoice> invoiceList = new List<Invoice>();
            invoiceList.Add(new Invoice() { InvoiceSerialID = invoiceSerialID, AuditPerson = CurrentAccount.GetUser().UserID });
            //DistributionSerialID= Request.Form["ChkOrderID"].ToString().Split(',');
            int state = iPurchase.ConfirmInvoice_Batch(invoiceList, DistributionSerialID);
            if (state == 1)
            {
                HZ.Web.WebUtil.Alert("成功将发票提交给医疗机构！", this);
            }
            else if (state == 2)
            {
                HZ.Web.WebUtil.Alert("发票明细中有未处理的退货单！", this);
            }
            else
            {
                HZ.Web.WebUtil.Alert("操作失败！", this);
            }
            ShowData();
            ShowInvocieInfo();
        }

        protected void btnDrop_Click(object sender, EventArgs e)
        {


            IList<Model.View.InvoiceDistribution> ListInvoiceDistribution = new List<Model.View.InvoiceDistribution>();
            Model.Query.InvoiceDistribution qryCondition = new Model.Query.InvoiceDistribution();
            User user = CurrentAccount.GetUser();
            qryCondition.CompanyID_PS = user.Org.OrgID;
            qryCondition.InvoiceSerialID = invoiceSerialID;


            int totalCount = 0;
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            ListInvoiceDistribution = iPurchase.GetInvoiceDistributionByWhere(qryCondition, 1, 0, out totalCount);
            if (ListInvoiceDistribution.Count == 0)
            {
                HZ.Web.WebUtil.Alert("空发票！");
                return;
            }
            if (ListInvoiceDistribution[0].InvoicePaySerialID != null && ListInvoiceDistribution[0].InvoicePaySerialID.Trim() != string.Empty)
            {
                HZ.Web.WebUtil.Alert("已建立结算单的发票不能撤回！");
                return;
            }
            if (ListInvoiceDistribution[0].AuditStatus == 0)
            {
                HZ.Web.WebUtil.Alert("此发票还未提交！");
                return;
            }


            List<Invoice> invoiceList = new List<Invoice>();
            invoiceList.Add(new Invoice() { InvoiceSerialID = invoiceSerialID, AuditStatus = 0, AuditPerson = CurrentAccount.GetUser().UserID });
            int state = iPurchase.DropInvoice_Batch(invoiceList);
            if (state == 1)
            {
                HZ.Web.WebUtil.Alert("成功撤回发票！", this);

            }
            else if (state == 2)
            {
                HZ.Web.WebUtil.Alert("已建立结算单的发票不能撤回！", this);

            }
            else
            {
                HZ.Web.WebUtil.Alert("操作失败！", this);
            }
            ShowData();
            ShowInvocieInfo();
        }
    }
}
